//------------------------------------------------------------------------------
//  <copyright file="KinectObjectDetectorIRAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Vision.Runtime
{
    using System;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;
    using System.Windows;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision.Cameras;
    using Microsoft.Robotics.Vision.ObjectDetection;
    using Microsoft.Robotics.Vision.Runtime.Cameras;

    /// <summary>
    /// runs object detection on Kinect depth plus IR image frames
    /// </summary>
    [DataContract]
    public class KinectObjectDetectorIRAgent : ConsumerProducerAgent<DepthIRColorCameraMessage<DepthParameters, IRParameters, ColorParameters>, KinectObjectDetectorResultIRMessage>
    {
        /// <summary>
        /// Path to the detector configuration files
        /// </summary>
        [DataMember(Name = "DetectorConfigurationFiles")]
        public readonly string[] DetectorConfigurationFiles;

        /// <summary>
        /// Initializes a new instance of the <see cref="KinectObjectDetectorIRAgent" /> class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="producer">Upstream producer</param>
        /// <param name="detectorConfigurationFiles">Configuration files for the object detector</param>
        public KinectObjectDetectorIRAgent(
            string name,
            IProducer<DepthIRColorCameraMessage<DepthParameters, IRParameters, ColorParameters>> producer,
            string[] detectorConfigurationFiles)
            : base(name, producer.Name)
        {
            this.DetectorConfigurationFiles = detectorConfigurationFiles;
        }

        /// <summary>
        /// Gets or sets context for the sequencer FSM that manages kinect frame acquisition and object detection
        /// </summary>
        protected KinectObjectDetectorContext KinectDetectorContext { get; set; }

        /// <summary>
        /// Gets or sets the sequencer FSM to manage kinect frame acquisition and running object detection
        /// </summary>
        protected KinectObjectDetectorSequencer KinectDetectorSequencer { get; set; }

        /// <summary>
        /// Initializes the agent instance
        /// </summary>
        /// <param name="locator">A locator that the agent can use to discover other agents</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
        }

        /// <summary>
        /// Called when the agent is about to end
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
            if (null != this.KinectDetectorContext)
            {
                this.KinectDetectorContext.Dispose();
            }
        }

        /// <summary>
        /// Handles reception of the kinect message
        /// </summary>
        /// <param name="message">Received kinect message</param>
        public override void Receive(DepthIRColorCameraMessage<DepthParameters, IRParameters, ColorParameters> message)
        {
            if (null != message.DepthCamera && null != message.IRCamera)
        {
            if (null == this.KinectDetectorContext || null == this.KinectDetectorSequencer)
            {
                this.InitializeSequencer(message);
            }

                this.KinectDetectorContext.SaveImageFrames(message.DepthFrame, message.IRFrame, message.OriginatingTime);
            this.KinectDetectorSequencer.Step();
        }
        }

        /// <summary>
        /// Post object detection results
        /// </summary>
        public void PostDetectionResult()
        {
            if (null != this.KinectDetectorContext.DetectionResults)
            {
                KinectObjectDetectorResultIRMessage result = new KinectObjectDetectorResultIRMessage(
                    this.KinectDetectorContext.LastUsedFrameOriginatingTime,
                    this.KinectDetectorContext.LastUsedDepthFrame,
                    this.KinectDetectorContext.LastUsedIRframe,
                    this.KinectDetectorContext.DetectionResults);
                this.Publisher.Post(result);
                this.KinectDetectorContext.LastDetectionPostTime = AgentMessage.GetCurrentTime();
            }
        }

        /// <summary>
        /// Initialize detector FSM sequencer
        /// </summary>
        /// <param name="message">Kinect agent message containing kinect camera intrinsic and extrinsic parameters</param>
        private void InitializeSequencer(DepthIRColorCameraMessage<DepthParameters, IRParameters, ColorParameters> message)
        {
            if (null != message.DepthCamera)
        {
            this.KinectDetectorContext = new KinectObjectDetectorContext(
                                            this.DetectorConfigurationFiles,
                                                message.DepthCamera.Parameters.Pose,
                                                message.DepthCamera.Parameters.Intrinsics);

            this.KinectDetectorSequencer = new KinectObjectDetectorSequencer(this.KinectDetectorContext);
            this.KinectDetectorContext.PostDetectionResult = this.PostDetectionResult;
        }
    }
}
}
